<template>
	<view class="index">
		<view class="box">
			<view class="boxcode">
				<view class="desbg">
					<view class="titleView">
						<text class="qrTitle">财政电子票据</text>
					</view>
					<view class="nextView">
						<view>
							<view class="qrcell">
								<image class="qrimage" src="/static/assets/qrcode.png" mode="widthFix"></image>
								<text class="qrtext">票据代码</text>
							</view>
							<view class="codevalue">{{ einvoiceCode }}</view>
						</view>
						<view class="coderight">
							<view class="qrcell">
								<image class="qrimage" src="/static/assets/codeprice.png" mode="widthFix"></image>
								<text class="qrtext">票据金额</text>
							</view>
							<view class="codevalue">￥{{ totalAmount }}</view>
						</view>
					</view>
				</view>
				<view class="xuxianView">
					<image class="xuxian" src="/static/assets/xuxian.png" mode="widthFix"></image>
				</view>
				<view class="erweimaView">
					<!-- <canvas 
            class="scanCode" 
            canvas-id="myQrcode"
          ></canvas> -->
					<u-image :src="qrCode" mode="aspectFit"></u-image>
					<view class="saoyisao">电子票簿小程序 扫一扫</view>
				</view>
				<view class="savebtn" @click="saveBase64Image">保存二维码图片</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		postGetqrcode
	} from '@/api/ticketApi.js'
	export default {
		data() {
			return {
				einvoiceCode: '',
				totalAmount: '',
				qrCode: '',
			}
		},
		onLoad(options) {
			// 获取页面参数
			const {
				einvoiceCode,
				totalAmount,
				einvoiceNumber,
				randomNumber
			} = JSON.parse(decodeURIComponent(options.item));
			this.fetch(einvoiceCode, einvoiceNumber, randomNumber, totalAmount);
		},
		methods: {
			async fetch(einvoiceCode, einvoiceNumber, randomNumber, totalAmount) {
				try {
					uni.showLoading({
						title: '加载中'
					})
					const param = {
						einvoiceCode,
						einvoiceNumber,
						randomNumber
					}
					const res = await postGetqrcode(param)
					if (res.data.result == 0) {
						this.einvoiceCode = res.data.number
						this.totalAmount = totalAmount
						this.qrCode = 'data:image/png;base64,' + res.data.qrcode
					}
				} catch (error) {
					uni.$u.toast(error.data.message || '接口错误')
					console.error('接口请求失败', error)
				} finally {
					uni.hideLoading()
				}
			},
			// 保存base64图片主方法
			saveBase64Image() {
				// 1. 处理base64数据（去掉前缀，如"data:image/png;base64,"）
				const base64Data = this.qrCode.replace(/^data:image\/\w+;base64,/, '');

				// 2. 生成临时文件路径（微信小程序本地临时路径格式）
				const filePath = `${wx.env.USER_DATA_PATH}/temp_image.png`; // 固定格式，后缀根据图片类型修改（如.jpg/.png）

				// 3. 获取文件系统管理器
				const fs = wx.getFileSystemManager();

				try {
					// 4. 将base64写入本地文件
					fs.writeFile({
						filePath: filePath,
						data: base64Data,
						encoding: 'base64', // 必须指定编码为base64
						success: () => {
							// 5. 写入成功后，调用保存图片API
							this.saveToAlbum(filePath);
						},
						fail: (err) => {
							console.error('写入文件失败：', err);
							uni.showToast({
								title: '保存失败',
								icon: 'none'
							});
						}
					});
				} catch (e) {
					console.error('处理base64出错：', e);
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					});
				}
			},

			// 保存到相册（复用之前的保存逻辑）
			saveToAlbum(tempFilePath) {
				wx.saveImageToPhotosAlbum({
					filePath: tempFilePath,
					success: () => {
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						});
					},
					fail: (err) => {
						// 处理授权失败（同之前的逻辑）
						if (err.errMsg.includes('auth deny') || err.errMsg.includes('permission denied')) {
							uni.showModal({
								title: '授权提示',
								content: '需要您授权保存图片到相册',
								success: (modalRes) => {
									if (modalRes.confirm) {
										wx.openSetting({
											success: (settingRes) => {
												if (settingRes.authSetting[
														'scope.writePhotosAlbum']) {
													uni.showToast({
														title: '授权成功，请重新保存',
														icon: 'none'
													});
												}
											}
										});
									}
								}
							});
						} else {
							uni.showToast({
								title: '保存失败',
								icon: 'none'
							});
						}
					}
				});
			}
		}
	}
</script>

<style scoped>
	/* 引入uView样式（通常在App.vue中全局引入） */
	/* @import "uview-ui/index.scss"; */

	.index {
		width: 100%;
		min-height: 100vh;
		background-color: white;
	}

	.box {
		width: 100%;
		min-height: 100vh;
		display: flex;
		flex: 1;
		background: linear-gradient(-30deg, rgba(67, 138, 255, 1), rgba(55, 101, 255, 1));
		flex-direction: column;
		align-items: center;
	}

	.boxcode {
		margin-top: 69rpx;
		width: 690rpx;
		height: 903rpx;
		background: url('');
		background-size: 100%;
	}

	.desbg {
		height: 258rpx;
		width: 100%;
		display: flex;
		flex-direction: column;
	}

	.titleView {
		width: 100%;
		height: 98rpx;
		display: flex;
		justify-content: center;
		align-items: flex-end;
	}

	.qrTitle {
		font-size: 40rpx;
		font-weight: 500;
		color: rgba(34, 34, 34, 1);
	}

	.nextView {
		width: 100%;
		height: 161rpx;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}

	.coderight {
		margin-left: 126rpx;
	}

	.qrcell {
		flex: 1;
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.qrimage {
		width: 34rpx;
		height: 34rpx;
	}

	.qrtext {
		margin-left: 9rpx;
		font-size: 26rpx;
		font-weight: 400;
		color: rgba(153, 153, 153, 1);
	}

	.codevalue {
		margin-top: 8rpx;
		font-size: 30rpx;
		font-weight: 500;
		color: rgba(34, 34, 34, 1);
	}

	.xuxianView {
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.xuxian {
		width: 638rpx;
		height: 1rpx;
	}

	.erweimaView {
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		margin-top: 67rpx;
	}

	.scanCode {
		width: 431rpx;
		height: 431rpx;
	}

	.saoyisao {
		margin-top: 37rpx;
		font-size: 30rpx;
		font-weight: 400;
		color: rgba(153, 153, 153, 1);
	}

	.savebtn {
		margin-top: 126rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 690rpx;
		height: 98rpx;
		background: rgba(255, 255, 255, 1);
		border-radius: 49rpx;
		font-size: 34rpx;
		font-weight: 400;
		color: rgba(55, 101, 255, 1);
	}
</style>